package RTS.net;


import java.net.*;
import java.io.*;

public class KnockKnockServer {
    public static void main(String[] args) throws IOException {

        try {
            InetAddress localaddr = InetAddress.getLocalHost();
            System.out.println ("Hostname : " + localaddr.getHostAddress() );
	} catch (UnknownHostException e) {
            System.err.println ("Can't detect localhost : " + e);
	}

        ServerSocket serverSocket = null;

        int portNumber = 4444;

        while (serverSocket == null ) {
            try {
                serverSocket = new ServerSocket(portNumber);
            } catch (IOException e) {
                System.err.println("Could not listen on port: 4444.");
                portNumber++;
            }
        }

        System.out.println ("Connected on port "+portNumber+".");

        Socket clientSocket = null;
        try {
            clientSocket = serverSocket.accept();
            System.out.println ("Client connected.");
        } catch (IOException e) {
            System.err.println("Accept failed.");
            System.exit(1);
        }

        PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
        BufferedReader in = new BufferedReader(
				new InputStreamReader(
				clientSocket.getInputStream()));
        String inputLine, outputLine;

        BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));

        outputLine = "Connection established.";
        out.println(outputLine);

        int i = 0;

        while ((inputLine = in.readLine()) != null) {
             System.out.println("Client says: " + inputLine);
             System.out.print("Server says: ");
             String serverSays = stdIn.readLine();
             i++;
             out.println(serverSays);
             if (serverSays.equals("Bye."))
                break;
        }
        out.close();
        in.close();
        clientSocket.close();
        serverSocket.close();
    }
}